package com.library.web.controller.common;

import com.library.common.config.LibraryConfig;
import com.library.common.constant.Constants;
import com.library.common.core.domain.AjaxResult;
import com.library.common.utils.StringUtils;
import com.library.common.utils.file.FileUploadUtils;
import com.library.common.utils.file.FileUtils;
import com.library.common.utils.file.MultipartFileDto;
import com.library.common.utils.uuid.UUID;
import com.library.common.wspoint.point.GlobalServerPoint;
import com.library.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 通用请求处理
 * 
 * @author hb
 */
@Api(tags = "通用请求处理")
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Resource
    private ServerConfig serverConfig;

    @Resource
    private GlobalServerPoint globalServerPoint;

    @Resource
    private RestTemplate restTemplate;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @ApiOperation("通用下载请求")
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = LibraryConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @ApiOperation("通用上传请求（单个）")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try
        {
            // 上传文件路径
            String filePath = LibraryConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @ApiOperation("通用上传请求（多个）")
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) {
        try
        {
            // 上传文件路径
            String filePath = LibraryConfig.getUploadPath();
            List<String> urls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            List<String> newFileNames = new ArrayList<>();
            List<String> originalFilenames = new ArrayList<>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @ApiOperation("本地资源通用下载")
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletResponse response) {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = LibraryConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 本地资源通用下载
     */
    @ApiOperation("本地资源通用下载")
    @PostMapping("/test")
    public AjaxResult resourceDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String s = StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset());
        return AjaxResult.success(s);
    }

    /***
     * 下载图片
     * @param map
     * @return
     * @throws IOException
     */
    @PostMapping("/imgdown")
    public AjaxResult imgDown(@RequestBody Map<String,Object> map) throws IOException {
        String isbn = map.get("isbn").toString();
        List<Object> uris = (List<Object>) map.get("req");
        List<String> urls = new ArrayList<>();
        for (Object uri : uris) {
            try{
                HttpHeaders multiValueMap = new HttpHeaders();
                multiValueMap.set("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36");
                ResponseEntity<byte[]> forEntity = restTemplate.exchange(URI.create(String.valueOf(uri)), HttpMethod.GET, new HttpEntity<>(multiValueMap), byte[].class);
                byte[] body = forEntity.getBody();
                // 能否读到图片数据
                if(body != null) {
                    // E:xxxx/download/{isbn}
                    String dir =String.format("%shistory/%s",LibraryConfig.getDownloadPath(),isbn);
                    MediaType contentType = forEntity.getHeaders().getContentType();
                    if(MediaType.IMAGE_JPEG.includes(contentType)) {
                        log.info("图片下载MediaType：{}",contentType);
                        MultipartFileDto multipartFileDto = new MultipartFileDto("file",UUID.fastUUID().toString() + ".png",contentType.toString(),forEntity.getBody());
                        String uploadPath = FileUploadUtils.upload(dir, false , multipartFileDto);
                        urls.add(uploadPath);
                    }
                }
            }catch (Exception e){
                log.error("图片下载失败:[src={}]",uri);
                e.printStackTrace();
            }
        }
        // 是否有保存的图片
        if(urls.isEmpty()) {
            return AjaxResult.error("图片下载失败");
        }
        return AjaxResult.success(urls);
    }

    @GetMapping("/closeWs")
    public void closeWs(String key) {
        globalServerPoint.close(key);
    }

}
